import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { Card, Table, Button, Modal, message, Select } from 'antd';
import { connect } from 'dva';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import Ellipsis from '../../../components/Ellipsis';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { filterAuth } from '@/support/common';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import router from 'umi/router';
import moment from 'moment';

const mapStateToProps = (state: any) => ({
  modelGroup: state.modelGroup,
  loading: state.loading.models['modelGroup/getFetchPage'],
  menu: state.menu,
});
let pageObj = {};
class ModelGroup extends PureComponent<any, any> {
  static contextTypes = {};

  state = {
    formValues: {},
    seriesOptions: [], //车系数据
    brandOptions: [],
    defaultBrand: '',
    selectBrand: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
     //获取品牌数据
     dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data,
          });
          if(this.props.location.state&&this.props.location.state.sourceRouter == 'modelGroup'){
            const brandData = JSON.parse(sessionStorage.getItem('modelGroupBrandInfo')||'{}');
            const brandId = brandData&&brandData?.selectBrand
            this.setState({ 
              defaultBrand: brandId,
              selectBrand: brandId
             });
             this.getSeriesList(brandId);
             this.getList(brandId);
          }else{
            this.setState({ 
              defaultBrand: res?.data[0].brandCode,
              selectBrand: res?.data[0].brandCode
             });
          this.getSeriesList(res?.data[0].brandCode);
          this.getList(res?.data[0].brandCode);
          }
        }
    });
  }
  //获取车系数据
 getSeriesList = (brandId:String)=>{
   // 获取车系数据
   const { dispatch } = this.props;
   const { formValues } = this.state;
   dispatch({
     type: 'modelGroup/getDataWithRes',
     payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
     callback: e => {
       if (e.data) {
         this.setState({
           seriesOptions: e.data.map(e => ({
             label: e.seriesName,
             value: e.seriesCode,
           })),
         });
       }
     },
   });
 }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'modelGroup/initData',
    });
  }
  getList=(brandId:String)=> {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'modelGroup/getFetchPage',
      payload: { url: '/device/vehicle/group/findList', brandId:brandId },
    });
  }
  handleFormReset = () => {
    this.searchForm.current.setFieldsValue({});
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues, selectBrand } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      curPage: current,
      pageSize: pageSize,
      brandId: selectBrand,
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'modelGroup/getFetchPage',
      payload: { url: '/device/vehicle/group/findList', ...params },
    });
  };
  handleDelete = (key: any) => {};
  handleAdd = (record: any) => {
    const { dispatch } = this.props;
    const { formValues, selectBrand } = this.state;
    const searchValues = {
      ...formValues,
      selectBrand
    };
    sessionStorage.setItem('modelGroupBrandInfo', JSON.stringify(searchValues));
    if (record && record.sid) {
      sessionStorage.setItem('modelGroupData', JSON.stringify(record));
      router.push({
        pathname: '/remoteConfiguration/modelGroup/modelGroupEdit',
        state: { pageObj: pageObj, formValues, backUrl: '/remoteConfiguration/modelGroup',brandOption: this.state.brandOptions, brandId: this.state.selectBrand },
      });
    } else {
      sessionStorage.setItem('modelGroupData', '');
      router.push({
        pathname: '/remoteConfiguration/modelGroup/modelGroupAdd',
        state: { pageObj: pageObj, formValues, backUrl: '/remoteConfiguration/modelGroup',brandOption: this.state.brandOptions, brandId: this.state.selectBrand },
      });
    }
  };
  postDelete = (key: any) => {
    const { dispatch } = this.props;
    const {selectBrand}=this.state;
    dispatch({
      type: 'modelGroup/postDataWithRes',
      payload: { url: '/vehicle/group/delete/' + key },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功！');
          this.getList(selectBrand);
        }
        // else {
        //   message.error(res.statusMessage);
        // }
      },
    });
  };
  onBrandSelect = (value:any) =>{
    this.setState({
      selectBrand: value,
      formValues: {},
    })
    this.searchForm.current.resetFields();
    this.getList(value);
    this.getSeriesList(value);
  };
  render() {
    const {
      modelGroup: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
      menu: { permissions },
    } = this.props;
    const { seriesOptions,brandOptions,defaultBrand, selectBrand } = this.state;
    const options = brandOptions.map((item:any)=>{
      return {
        label: item.brandName,
        value: item.brandCode
      }
    })
    pageObj = pagination;
    const columns = [
      {
        title: '车系',
        dataIndex: 'series',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text.name}
            </Ellipsis>
          );
        },
      },
      {
        title: '车型组名称',
        dataIndex: 'groupName',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '操作人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        align: 'center',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'modelGroup_edit',
              onConfirm: () => this.handleAdd(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'modelGroup_delete',
              onConfirm: () => {
                let confirmLoading = false;
                Modal.confirm({
                  title: '删除',
                  content: (
                    <>
                      <p>确定要删除当前车型组吗？</p>
                    </>
                  ),
                  wrapClassName: 'layer-model-box',
                  icon: <ExclamationCircleOutlined />,
                  onOk: close => {
                    // 如果为重复点击
                    if (confirmLoading) {
                      return false;
                    }
                    confirmLoading = true;
                    // 点击删除请求接口
                    this.postDelete(record.sid);
                    // 关闭弹层
                    close();
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '车系',
        type: 'select',
        // customStyle: 6,
        selectOptions: seriesOptions,
        key: 'vehicleSeries',
      },
      {
        title: '车型组',
        type: 'input',
        key: 'name',
      },
    ];

    return (
      <div>
        <div  style={{margin: '0px 10px 10px 10px'}}>
          <div style={{display:'inline-block'}}>
          <span>品牌：</span>
            </div>
            <div style={{display:'inline-block'}}>
                 <Select
                    allowClear={false}
                    placeholder="请选择品牌"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    
                    onChange={this.onBrandSelect}
                    style={{width: '250px'}}
                    key={defaultBrand}
                    defaultValue={defaultBrand}
                    options={options}
                  >
                  </Select>
                  </div>
          </div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'modelGroup/getFetchPage', url: '/device/vehicle/group/findList' }}
            extraArgs={{ brandId: selectBrand,}}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          {filterAuth('modelGroup_add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增车型组
              </Button>
            </div>
          ) : null}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(ModelGroup);
